package controler;

import java.util.Observable;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import template.AbstractListener;

import model.Path;

import utils.Dom;

import org.jdom.Element;

public class ShowDeliveryPathListener extends AbstractListener implements
		ActionListener {

	private static final long serialVersionUID = 1L;
	private JList deliveriesOrderList;
	private JTextField emplacementTextField;
	private String buffer;
	public JFrame frame;

	public ShowDeliveryPathListener(Observable obs, JList jl, JTextField jtf) {
		addModel(obs);
		deliveriesOrderList = jl;
		emplacementTextField = jtf;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		try {
			Path pm = (Path) getModel(0);

			String startPoint = emplacementTextField.getText();

			if (startPoint.equals("")) {
				throw new Exception();
			}

			Element root = Dom.getXMLFile("bookOfDelivery.xml")
					.getRootElement();
			Element selectedDelivery = root.getChild("delivery"
					+ (deliveriesOrderList.getSelectedIndex() + 1));

			Element restRoot = Dom.getXMLFile("restaurants.xml")
					.getRootElement();
			buffer = selectedDelivery.getChildText("restaurant")
					.replaceAll(" ", "").toLowerCase().trim();
			Element seclectedRestAddress = restRoot.getChild(buffer);

			String stopPoint = seclectedRestAddress.getChild("address")
					.getChildText("civicaddress")
					+ ","
					+ seclectedRestAddress.getChild("address").getChildText(
							"city")
					+ ","
					+ seclectedRestAddress.getChild("address").getChildText(
							"country");

			String endPoint = selectedDelivery.getChildText("civicaddress")
					+ "," + selectedDelivery.getChildText("city") + ","
					+ selectedDelivery.getChildText("country");

			pm.setPoints(startPoint, stopPoint, endPoint);

		} catch (Exception e1) {
			System.out
					.println("No current emplacement, please re enter a valid emplacement");
			JOptionPane
					.showMessageDialog(frame,
							"No current emplacement, please re enter a valid emplacement");
		}
	}
}
